package com.nobody.facepk.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.nobody.facepk.model.Account;
import com.nobody.facepk.model.Friends;
import com.nobody.facepk.model.Match;
import com.nobody.facepk.model.Picture;
import com.nobody.facepk.model.User;
import com.nobody.facepk.pojo.SessionUser;
import com.nobody.facepk.service.EventService;
import com.nobody.facepk.service.ServiceRegistry;
import com.nobody.facepk.service.UserService;
import com.nobody.facepk.sns.Event;
import com.nobody.facepk.view.MatchView;

@Controller
public class UserController {
	private UserService userService;
	private EventService eventService;
	
	@RequestMapping("/register.do")
	public ModelAndView register(HttpServletRequest request,String userId,String password) {
		Account account = userService.register(userId, password);
		request.getSession().setAttribute("account", account);
		ModelAndView mav = null;
		mav = new ModelAndView("successReg");
		mav.addObject("account", account);
		return mav;
	}
	
	@RequestMapping("/registerUser.do")
	public ModelAndView registerUser(HttpServletRequest request,String mobile,String realname,String email) {
		Account accont = (Account)request.getSession().getAttribute("account");
		System.out.println("accont  ="+accont.getName());
		User user = userService.createUser(mobile,realname,email,accont);
		ModelAndView mav = null;
		mav = new ModelAndView("successRegUserInfo");
		mav.addObject("user", user);
		return mav;
	}
	@RequestMapping("/checkUser.do")
	public ModelAndView checkUser(HttpServletRequest request,HttpServletResponse response,String userName){
		String test = request.getParameter("userName");
		int ret = this.userService.checkUserByName(test);
		
		ModelAndView mav = new ModelAndView("plain");
		mav.addObject("data", ret==0?true:false+"");
//		try{
//			if(ret == 0){ //可以用
//				response.getWriter().write("true");
//			}else{
//				response.getWriter().write("false");
//			}
//		}catch(Exception e){
//			e.printStackTrace();
//		}
		return mav;
		
	}
	
	@RequestMapping("/loginAccount.do")
	public ModelAndView login(HttpServletRequest request ,String accountId,String password) {
		Account account = userService.login(accountId);
		ModelAndView mav = null;
		if(account!=null){
			if(account.getPasswd().equals(password) ){//密码正确
				mav = new ModelAndView("mySpace");
				Long userId = account.getUserId();
				User  user = userService.getUserById(userId);
				SessionUser sessionUser = new SessionUser();
				sessionUser.setUserId(userId);
				sessionUser.setName(user.getName());
				sessionUser.setMobile(user.getMobile());
				request.getSession().setAttribute("SESSION_USER",sessionUser);
				
				if(userId > 0){ //表示有扩展信息的用户
//					//得到用户的相册
//					List<Picture> pictures = ServiceRegistry.getPictureService().getPictures(userId);
//					mav.addObject("pictures",pictures);
//					//可以PK的照片
//					List<Picture> freePictures = ServiceRegistry.getPictureService().getFreePicturesById(userId);
//					mav.addObject("freePictures",freePictures);
					
					//取得最近评分完成的照片
					List<Picture> endScoringPictures = ServiceRegistry.getPictureService().getFriendsEndScoringPic(userId);
					
					//好友的正在评分的
					List<Picture> scoringPictures = ServiceRegistry.getPictureService().getFriendsScoringPic(userId);
					
				
					//获取好友列表
					Friends friends = this.userService.getMyFriends(userId);
					Set<Long> friendIds = friends.getFriendIds();
					List<User> myFriends = new ArrayList<User>();
					List<Event> events = new ArrayList<Event>();
					List<Long> friendMatchIds  = new ArrayList<Long>();
					List<Long> friendEndMatchIds  = new ArrayList<Long>();
					for(long friendId : friendIds){
						User userInfo = userService.getUserById(friendId);
						myFriends.add(userInfo);
						//新鲜事
						List<Event> friendEvents = this.eventService.getUserEvent(userInfo);
						if(friendEvents!=null){
							if(friendEvents.size() > 0 ){
								events.addAll(friendEvents);
							}
						}
						//获取我朋友正在PK的照片比赛Id集合
						List<Long> temp = (List)ServiceRegistry.getPictureService().getUserMatchIds(friendId);
						//获取我和我朋友PK结束的ID集合
						List<Long> endTemp = (List)ServiceRegistry.getPictureService().getUserEndMatchIds(friendId);
						if(temp != null){
							friendMatchIds.addAll(temp);
						}
						if(endTemp != null){
							friendEndMatchIds.addAll(endTemp);
						}
						//根据比赛集合ID 获取 相关信息
					}
					List<MatchView> list_mv = new ArrayList<MatchView>();
					List<MatchView> list_end_mv = new ArrayList<MatchView>();
					
					MatchView mv = null;
					for(long matchId : friendMatchIds){
						mv = new MatchView();
						//通过MATCH ID 得到比赛详情
						Match m = ServiceRegistry.getPictureService().getMatchByid(matchId);
						if(System.currentTimeMillis() <m.getTime()+24*(1000*3600)){
							Picture hostPic = ServiceRegistry.getPictureService().getPictureByid(m.getHostId());
							Picture guestPic = ServiceRegistry.getPictureService().getPictureByid(m.getGuestId());
							mv.setMatchId(matchId);
							mv.setHostId(m.getHostId());
							mv.setGuestId(m.getGuestId());
							mv.setHostPath(hostPic.getPath());
							mv.setGuestPath(guestPic.getPath());
							mv.setHostUserid(hostPic.getUserId());
							mv.setGuestUserid(guestPic.getUserId());
							list_mv.add(mv);
						}
					}
					for(long matchId : friendEndMatchIds){
						mv = new MatchView();
						//通过MATCH ID 得到比赛详情
						Match m = ServiceRegistry.getPictureService().getMatchByid(matchId);
						Picture hostPic = ServiceRegistry.getPictureService().getPictureByid(m.getHostId());
						Picture guestPic = ServiceRegistry.getPictureService().getPictureByid(m.getGuestId());
						
						mv.setMatchId(matchId);
						mv.setHostId(m.getHostId());
						mv.setGuestId(m.getGuestId());
						mv.setHostPath(hostPic.getPath());
						mv.setGuestPath(guestPic.getPath());
						mv.setHostUserid(hostPic.getUserId());
						mv.setGuestUserid(guestPic.getUserId());
						list_end_mv.add(mv);
					}
					//获取我的最近完成的PK
					List<Long> myEndTemp = (List)ServiceRegistry.getPictureService().getUserEndMatchIds(userId);
					if(myEndTemp != null){
						if(myEndTemp.size() > 0){
							for(long matchId : myEndTemp){
								mv = new MatchView();
								//通过MATCH ID 得到比赛详情
								Match m = ServiceRegistry.getPictureService().getMatchByid(matchId);
								Picture hostPic = ServiceRegistry.getPictureService().getPictureByid(m.getHostId());
								Picture guestPic = ServiceRegistry.getPictureService().getPictureByid(m.getGuestId());
								
								mv.setMatchId(matchId);
								mv.setHostId(m.getHostId());
								mv.setGuestId(m.getGuestId());
								mv.setHostPath(hostPic.getPath());
								mv.setGuestPath(guestPic.getPath());
								mv.setHostUserid(hostPic.getUserId());
								mv.setGuestUserid(guestPic.getUserId());
								list_end_mv.add(mv);
							}
						}
					
						
					}
					
					
					mav.addObject("list_end_mv",list_end_mv);
					mav.addObject("endScoringPictures",endScoringPictures);
					mav.addObject("scoringPictures",scoringPictures);
					mav.addObject("list_mv",list_mv);
					mav.addObject("events",events);
					mav.addObject("friends",myFriends);
					
					System.out.println("登陆用户是有效的");
				}
				
			}else{//密码错误
				mav = new ModelAndView("loginError");
			}
		}else{//账号为空
			mav = new ModelAndView("loginError");
		}
		return mav;
	}

	@RequestMapping("/loginByMobile.do")
	public ModelAndView loginByMobile(String mobile){
		User user = this.userService.getUserByMobile(mobile);
		long userId = user.getId();
		ModelAndView mav = null;
		if(userId > 0){ //表示有扩展信息的用户
			
			//取得最近评分完成的照片
			List<Picture> endScoringPictures = ServiceRegistry.getPictureService().getFriendsEndScoringPic(userId);
			
			//好友的正在评分的
			List<Picture> scoringPictures = ServiceRegistry.getPictureService().getFriendsScoringPic(userId);
			
		
			//获取好友列表
			Friends friends = this.userService.getMyFriends(userId);
			Set<Long> friendIds = friends.getFriendIds();
			List<User> myFriends = new ArrayList<User>();
			List<Event> events = new ArrayList<Event>();
			List<Long> friendMatchIds  = new ArrayList<Long>();
			for(long friendId : friendIds){
				User userInfo = userService.getUserById(friendId);
				myFriends.add(userInfo);
				//新鲜事
				List<Event> friendEvents = this.eventService.getUserEvent(userInfo);
				if(friendEvents!=null){
					if(friendEvents.size() > 0 ){
						events.addAll(friendEvents);
					}
				}
				//获取我朋友正在PK的照片比赛Id集合
				List<Long> temp = (List)ServiceRegistry.getPictureService().getUserMatchIds(friendId);
				if(temp != null){
					friendMatchIds.addAll(temp);
				}
			
				//根据比赛集合ID 获取 相关信息
			}
			List<MatchView> list_mv = new ArrayList<MatchView>();
			
			MatchView mv = null;
			for(long matchId : friendMatchIds){
				mv = new MatchView();
				//通过MATCH ID 得到比赛详情
				Match m = ServiceRegistry.getPictureService().getMatchByid(matchId);
				if(System.currentTimeMillis() <m.getTime()+24*(1000*3600)){
					Picture hostPic = ServiceRegistry.getPictureService().getPictureByid(m.getHostId());
					Picture guestPic = ServiceRegistry.getPictureService().getPictureByid(m.getGuestId());
					mv.setMatchId(matchId);
					mv.setHostId(m.getHostId());
					mv.setGuestId(m.getGuestId());
					mv.setHostPath(hostPic.getPath());
					mv.setGuestPath(guestPic.getPath());
					mv.setHostUserid(hostPic.getUserId());
					mv.setGuestUserid(guestPic.getUserId());
					list_mv.add(mv);
				}
			}
			mav = new ModelAndView("newSpace");
			mav.addObject("endScoringPictures",endScoringPictures);
			mav.addObject("scoringPictures",scoringPictures);
			mav.addObject("list_mv",list_mv);
			mav.addObject("events",events);
			mav.addObject("friends",myFriends);
			mav.addObject("user",user);
		
		}
		return mav;
	
	}
	
	
	
	@RequestMapping("/friendInfo.do")
	public ModelAndView friendInfo(HttpServletRequest request ,long friendId,boolean isMe) {
		User user = this.userService.getUserById(friendId);
		ModelAndView mav = null;
		if(user!=null){
			if(isMe){
				mav = new ModelAndView("mySpace");
			}else{
				mav = new ModelAndView("friendSpace");
			}
				if(friendId > 0){ //表示有扩展信息的用户
					//得到用户的相册
					List<Picture> pictures = ServiceRegistry.getPictureService().getPictures(friendId);
					mav.addObject("pictures",pictures);
					//正在评分的照片
					//List<Picture> scoringPictures = ServiceRegistry.getPictureService().getMyScoringPictures(userId)
					
					//好友的正在评分的
					List<Picture> scoringPictures = ServiceRegistry.getPictureService().getFriendsScoringPic(friendId);
					mav.addObject("scoringPictures",scoringPictures);
					
					//获取好友列表
					Friends friends = userService.getMyFriends(friendId);
					Set<Long> friendIds = friends.getFriendIds();
					List<User> myFriends = new ArrayList<User>();
					List<Event> events = new ArrayList<Event>();
					
					
					
					for(long id : friendIds){
						User userInfo = userService.getUserById(id);
						myFriends.add(userInfo);
						
						//获取好友动态
						List<Event> friendEvents = eventService.getUserEvent(userInfo);
						if(friendEvents!=null){
							if(friendEvents.size() > 0 ){
								events.addAll(friendEvents);
							}
						}
						
					}
					
					mav.addObject("friendInfo",user);
					mav.addObject("events",events);
					mav.addObject("friends",myFriends);
				}
		}
		return mav;
	}
	
	
	
	
	
	
	@RequestMapping("/addFriend.do")
	public ModelAndView addFriend(HttpServletRequest request , String mobile){
		
		SessionUser session = (SessionUser)request.getSession().getAttribute("SESSION_USER");
		long userid = session.getUserId();
		ModelAndView mav = null;
		if(mobile.equals(session.getMobile()))
		{ //就是加自己
			mav = new ModelAndView("error");
		}
		else
		{
			boolean isSuccess = userService.addFriend(mobile,userid);
			
			if(isSuccess){
				mav = new ModelAndView("myspace");
			}else{
				mav = new ModelAndView("error");
			}
		}
		
		return mav;
	}
	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	@Autowired
	public void setEventService(EventService eventService) {
		this.eventService = eventService;
	}
}
